<template>
  <van-cell class="comment-item">
    <van-image slot="icon" class="avatar" round fit="cover" :src="comments.aut_photo" />
    <div slot="title" class="title-wrap">
      <div class="user-name">{{ comments.aut_name }}</div>
      <van-button
        class="like-btn"
        @click="onCommentsLike"
        :icon="comments.like_count > 0 ? 'good-job' : 'good-job-o'"
        :class="comments.is_liking ? 'like' : ''"
        >{{ comments.like_count > 0 ? comments.like_count : '赞' }}</van-button
      >
    </div>

    <div slot="label">
      <p class="comment-content">{{ comments.content }}</p>
      <div class="bottom-info">
        <span class="comment-pubdate">{{ comments.pubdate | relativeTime }}</span>
        <van-button class="reply-btn" round>回复 {{ comments.reply_count }}</van-button>
      </div>
    </div>
  </van-cell>
</template>

<script>
import { addCommentLike, deleteCommentLike } from '@/api/comment.js'
import { mapState } from 'vuex'

export default {
  name: 'CommentItem',
  components: {},
  data() {
    return {}
  },
  computed: { ...mapState(['user']) },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onCommentsLike() {
      if (this.user) {
        try {
          // 1.判断当前评论用户是否点赞
          if (this.comments.is_liking) {
            // 2.点赞,发起取消点赞请求
            await deleteCommentLike(this.comments.com_id)
            this.comments.like_count-- // 评论数量减1
          } else {
            // 3.未点赞,发起点赞请求
            await addCommentLike(this.comments.com_id)
            this.comments.like_count++ // 评论数量加1
          }
          this.$toast.success(this.comments.is_liking ? '取消点赞' : '点赞成功')
          this.comments.is_liking = !this.comments.is_liking // 更新视图
        } catch (error) {
          console.log(error)
          this.$toast.fail('操作失败')
        }
      } else {
        this.$toast.fail('请先登录')
        this.$router.push('/login')
      }
    }
  },
  props: {
    comments: {
      type: Object,
      required: true
    }
  }
}
</script>

<style scoped lang="less">
.comment-item {
  .avatar {
    width: 72px;
    height: 72px;
    margin-right: 25px;
  }
  .title-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .user-name {
      color: #406599;
      font-size: 26px;
    }
  }
  .comment-content {
    font-size: 32px;
    color: #222222;
    word-break: break-all;
    text-align: justify;
  }
  .comment-pubdate {
    font-size: 19px;
    color: #222;
    margin-right: 25px;
  }
  .bottom-info {
    display: flex;
    align-items: center;
  }
  .reply-btn {
    width: 135px;
    height: 48px;
    line-height: 48px;
    font-size: 21px;
    color: #222;
  }
  .like-btn {
    height: 30px;
    padding: 0;
    border: none;
    font-size: 19px;
    line-height: 30px;
    margin-right: 7px;
    .van-icon {
      font-size: 30px;
    }
  }
  .like {
    color: #fa9f18 !important;
  }
}
</style>
